package cn.wolfcode.wechat.controller;

import cn.wolfcode.wechat.domain.Menu;
import cn.wolfcode.wechat.query.MenuQueryObject;
import cn.wolfcode.wechat.service.IMenuService;
import cn.wolfcode.wechat.util.AccessTokenUtil;
import cn.wolfcode.wechat.util.HttpUtil;
import cn.wolfcode.wechat.util.JSONResult;
import cn.wolfcode.wechat.util.UrlUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公众号菜单相关业务
 */
@Controller
public class MenuController {
    @Autowired
    private IMenuService menuService;

    /**
     * 获取所有菜单
     *
     * @param model
     * @return
     */
    @RequestMapping("menu")
    public String listMenu(Model model) {
        model.addAttribute("menus", menuService.getRootMenu());
        return "menu_list";
    }

    /**
     * 获取子菜单
     *
     * @param model
     * @return
     */
    @RequestMapping("menuItem")
    public String listMenuItem(Model model, @ModelAttribute("qo") MenuQueryObject qo) {
        model.addAttribute("menuGroups", menuService.getRootMenu());
        Long id = qo.getParentId();
        model.addAttribute("subMenuList", menuService.getSubMenu(id));
        return "menuItem_list";
    }

    @RequestMapping("menuLocalUpdate")
    @ResponseBody
    public JSONResult menuLocalUpdate(Menu menu) {
        try {
            menuService.saveOrUpdate(menu);
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, e.getMessage());
        }
    }

    /**
     * 调用接口更新菜单
     *
     * @return
     */
    @RequestMapping("menuRemoteUpdate")
    @ResponseBody
    public String updateMenu() {
        Map<String, Object> map = new HashMap<>();
        List<Menu> rootMenu = menuService.getRootMenu();
        map.put("button", rootMenu);
        String menuJson = JSON.toJSONString(map);
        String url = UrlUtil.MENU_CREATE_URL + "?access_token=" + AccessTokenUtil.getAccessTokenVo();
        String ret = HttpUtil.post(url, menuJson);
        return ret;
    }
}
